﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MyServer.Common;
using System.Net;
using System.Net.Sockets;
using FrameWork.Log;

namespace MyServer.TcpIP
{
    /// <summary>
    /// 表示一个基于TcpIp的收发中心
    /// </summary>
    public class TcpIpCenter : DataCenterBase
    {
        private object lockObj = new object();
        public new TcpIpDataReader Reader
        {
            get { return (TcpIpDataReader)base.Reader; }
            set { base.Reader = value; }
        }
        public new TcpIpDataSender Sender
        {
            get { return (TcpIpDataSender)base.Sender; }
            set { base.Sender = value; }
        }
        public new TcpIpConnectManager ConnectionManager
        {
            get { return (TcpIpConnectManager)base.ConnectionManager; }
            set { base.ConnectionManager = value; }
        }

        public new TcpIpDataListener Listener
        {
            get { return (TcpIpDataListener)base.Listener; }
            set { base.Listener = value; }
        }

        /// <summary>
        /// 获取Tcp收发中心关联的本地终结点
        /// </summary>
        public IPEndPoint BindEndPoint { get; private set; }

        /// <summary>
        /// 通过Tcp收发中心向指定客户端发送数据
        /// </summary>
        /// <param name="RemoteClient">远程客户端实例</param>
        /// <param name="Data">要发送的数据</param>
        /// <param name="pkgName">数据包列表名称</param>
        public void SendData(TcpClient RemoteClient, byte[] Data, string pkgName, bool IsRecive = false)
        {
            lock (lockObj)
            {
                if (RemoteClient == null)
                    return;
                DataPackageCollection pkg = DataPacker.PackData(Data, 1400, pkgName);
                pkg.Tag = RemoteClient;
                Sender.AddToQueue(pkg);
                if (IsRecive)
                {
                    Listener.AddConnect(RemoteClient);
                }
            }
        }

        /// <summary>
        /// 通过指定终结点信息创建Tcp收发中心实例
        /// </summary>
        /// <param name="LocalPoint"></param>
        public TcpIpCenter(IPEndPoint LocalPoint, DataOperatorBase oper = null, DataCompressorBase Compressor = null)
        {
            PrintLog(LogType.Info, "正在初始化Tcp收发中心...");
            Reader = new TcpIpDataReader(this, Compressor);
            Sender = new TcpIpDataSender(this, Compressor);
            ConnectionManager = new TcpIpConnectManager(LocalPoint, this);
            this.BindEndPoint = LocalPoint;

            if (oper == null)
            {
                PrintLog(LogType.Waring, "未指定自定义数据处理器，将使用默认数据处理器！");
                Operator = new TcpIpOperator(this);
            }
            else
                Operator = oper;

            Listener = new TcpIpDataListener(this);
            PrintLog(LogType.Info, "Tcp收发中心初始化成功！");
        }

    }
}
